#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>

#define NUM 3

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//将互斥量定义为全局变量

int tickets = 50;//票的张数
class ThreadData
{
    public:
    ThreadData(int num)
    {
        threadname = "thread-" + std::to_string(num);
    }
    ~ThreadData()
    {}
    public:
    std::string threadname;
};

void* GetTicket(void* arg)
{
    pthread_detach(pthread_self());//分离线程
    ThreadData* td = static_cast<ThreadData*>(arg);
    while(true)
    {
        pthread_mutex_lock(&mutex);//申请加锁成功才能往后执行，否则阻塞
        if(tickets>0)
        {
            std::cout<<td->threadname<<" grep"<<tickets<<std::endl;
            --tickets;
            pthread_mutex_unlock(&mutex);//解锁
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    std::cout<<td->threadname<<" is exit"<<std::endl;
    return nullptr;
}

int main()
{
std::vector<ThreadData*> thread_datas;
    for(int i =1;i<=NUM;i++)
    {
        ThreadData* td = new ThreadData(i); //要在堆上开辟数据，要传入新线程的启动函数里，新线程共享主进程的堆数据
        thread_datas.push_back(td);
        pthread_t tid;
        pthread_create(&tid, nullptr, GetTicket, td);
    }
    for(auto e:thread_datas)
    {
        delete e;
    }
    return 0;
}